package com.assisjrs.jpaandroid.sample.basic;

import android.app.Activity;
import android.os.Bundle;

import com.assisjrs.jpaandroid.persistence.Entity;
import com.assisjrs.jpaandroid.persistence.EntityManager;
import com.assisjrs.jpaandroid.persistence.ModelDefinition;

public abstract class CrudActivity<T extends Entity> extends Activity {
	public static final String INSTANCE_EXTRA = "instance";

	protected EntityManager entityManager;
	protected T instance;
	protected Long id;

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		bindToView();
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (id == null)
			try {
				id = getIntent().getExtras().getLong(ModelDefinition.ID_NAME);
				if (id == null || id < 1)
					getInstance();
				else
					instance = (T) entityManager.find(instance.getClass(), id);
			} catch (final Exception e1) {
				getInstance();
			}
		else
			instance = (T) entityManager.find(instance.getClass(), id);

		instanceToView(instance);
	}

	@SuppressWarnings("unchecked")
	private void getInstance() {
		try {
			instance = (T) getIntent().getExtras().get(INSTANCE_EXTRA);
			id = instance.getId();
		} catch (final Exception e2) {
			id = null;
			instance = (T) entityManager.find(instance.getClass(), id);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		salvar();
	}

	protected void salvar() {
		if (instance == null || id != null)
			instance = (T) entityManager.find(instance.getClass(), id);

		instance.setId(id);
		viewToInstance(instance);
		entityManager.merge(instance);
	}

	protected abstract void instanceToView(T instance);
	protected abstract void viewToInstance(T instance);
	protected abstract void bindToView();
}
